package de.uniulm.muc.mensafinder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class SearchActivity extends Activity {
	
	private static Calendar calendar = Calendar.getInstance();
	
	/**
	 * Stores the users with their orientations and ages that are logged on.
	 */
	private Map<String, UserDetails> registeredUsers = null;
	
	private Date lastUpdate = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // try to get logged on users from server
        if(!getSnapshot()) {
        	// TODO: notify user first (AlertDialog) then quit if no proper response from server received
        	finish();
        }
        if(!startStreaming()) {
        	// TODO: notify user first (AlertDialog) then quit if no proper response from server received
        	finish();
        }
        setContentView(R.layout.search);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    }
    
    public void searchFriends(View v) {
        Log.i("MensaFinder", "Search friends started");
    }

    public void returnToMain(View v) {
        Log.i("MensaFinder", "Return to main");
        this.setResult(1);
        this.finish();
    }
    
    /**
     * This method retrieves all currently registered devices from the server.
     * Therefore it uses the "snapshot"-service provided from the server.
     * The result is stored in a map of <String, Integer>.
     */
    private boolean getSnapshot() {
    	String uri = "http://barracuda-vm8.informatik.uni-ulm.de/orientations/snapshot";

		int timeoutConnection = 3000;
		int timeoutSocket = 3000;
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		
		HttpClient client = new DefaultHttpClient(httpParameters);
		HttpGet request = new HttpGet(uri);
		HttpResponse response;
		try {
			response = client.execute(request);
			HttpEntity entity = response.getEntity();
			System.out.println(entity.getContentType().getValue());	//TODO: delete after testing
			
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				Log.i("MensaFinder", "Received user list from server (snapshot)");
				// create a new HashMap to store the users and their orientations
				registeredUsers = new HashMap<String, UserDetails> ();
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
				    builder.append(line).append("\n");
				}
				JSONTokener tokener = new JSONTokener(builder.toString()); 
				JSONObject rootObject = new JSONObject(tokener);
				
				// store the received timestamp (later needed for "if-modiefied-since)
				String timeString = rootObject.getString("time");
				String[] temp = timeString.split("T");
				String[] date = temp[0].split("-");
				String[] time = temp[1].split(":");
				calendar.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]),
						Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]),
						Integer.parseInt(time[2].split(".")[0]));
				lastUpdate = calendar.getTime();
				
				// Insert all found users into Map
				JSONArray users = rootObject.getJSONArray("list");
				for(int i = 0; i < users.length(); i++) {
					JSONObject object = users.getJSONObject(i);
					String username = object.getString("user");
					int orientation = object.getInt("orientation");
					// translate age value (in seconds) in Date
					int age = object.getInt("age");
					calendar.setTimeInMillis(lastUpdate.getTime() - age * 1000);
					Date since = calendar.getTime();
					// add this user to the map
					registeredUsers.put(username, new UserDetails(orientation, since));
				}
				return true;
			} else {
				Log.i("MensaFinder", "GET Request (snapshot) failed!");
				return false;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}
    }
    
    /**
     * This enables the application to receive updates from the server about users orientations.
     * @return
     */
    private boolean startStreaming() {
    	String uri = "http://barracuda-vm8.informatik.uni-ulm.de/orientations/stream";

	/*	int timeoutConnection = 3000;
		int timeoutSocket = 3000;
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		
		HttpClient client = new DefaultHttpClient(httpParameters);
		HttpGet request = new HttpGet(uri);
		HttpResponse response;
	*/	
		// Use Restlet Framework
    	
		// TODO: how to get updates?
		ClientResource cr = new ClientResource(uri); 
		Representation responseEntity = cr.getResponseEntity();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getStream()));
			StringBuilder builder = new StringBuilder();
			for (String line = null; (line = reader.readLine()) != null;) {
			    builder.append(line).append("\n");
			}
			JSONTokener tokener = new JSONTokener(builder.toString()); 
			JSONObject rootObject = new JSONObject(tokener);
			
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}
		return true;
    }
    
}